import telnetlib
import logging
import os
run_log = 'run.txt'
if os.path.exists(run_log):
    os.remove(run_log)
logger = logging.getLogger()
logger.setLevel('DEBUG')
BASIC_FORMAT = "%(asctime)s :%(levelname)s :%(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
chlr = logging.StreamHandler() # 输出到控制台的handler
chlr.setFormatter(formatter)
chlr.setLevel('DEBUG')  # 也可以不设置，不设置就默认用logger的level
fhlr = logging.FileHandler(run_log) # 输出到文件的handler
fhlr.setFormatter(formatter)
logger.addHandler(chlr)
logger.addHandler(fhlr)

##telnet访问函数
def to_up(Host, port, timeout, frequency):
    info = ("第[%s]次访问地址[%s:%s]" %(frequency, Host, port))
    try:
        tn = telnetlib.Telnet(Host, port=port, timeout=timeout)
        tn.close()
        de = info + "成功\n"
        logger.debug(de)
    except:
        err = info + "失败\n"
        logger.error(err)


#测试功能类    
class Test:
    def __init__(self, frequency, port, timeout, host):
        self.frequency = frequency
        self.host = host
        self.port = int(port)
        self.timeout = int(timeout)
    def telnet(self):
        end = self.frequency + 1
        for s in range(1, end):
            to_up(Host=self.host, port=self.port, timeout=self.timeout, frequency=s)
    def ping(self):
        pass

#获取程序信息    
def get_info(url_file, types, frequency=1, timeout=None):
    if os.path.exists(url_file):
        # 打开文件
        file = open(url_file, "r", encoding='utf-8')
        # 遍历文件行内容
        for (num, line) in enumerate(file, 1):
            line = str.replace(line,'\n','')
            logger.info("正在检测第[%s]行内容:[%s]" % (num, line))
            xi2 = [line]
            for i in xi2:
                domain_port = i.split(' ')
                domain = domain_port[0]
                port = domain_port[1]
                logger.info("第[%s]行获取的域名：[%s]" % (num, domain))
                logger.info("第[%s]行获取的端口：[%s]\n" % (num, port))
                if types == 'telnet':
                    Program = Test(frequency=frequency, port=port, timeout=timeout, host=domain)
                    Program.telnet()
        file.close()
    else:
        exit("找不到文件[%s]" %url_file)

##入口菜单类
class menu:
    def __init__(self):
        pass
    def telnet(self):
        file = input('请输入主机:端口信息存放文件路径,默认:[ ./list.txt ]:\n')
        timeout = input("请设置数据请求超时时间[单位:秒],默认[ 3 ]:\n")
        frequen = input("请输入测试的次数[整数],默认[ 3 ]:\n")
        if not file:
            file = './list.txt'
        if timeout:
            pass
        else:
            timeout = 3
        if frequen:
            pass
        else:
            frequen = 3
        get_info(url_file=file, types='telnet', timeout=timeout, frequency=int(frequen))
me = input('请选择一个菜单:\n[1]Telnet\n')
starts = menu()
if me == "1":
    starts.telnet()
